package fzdy.controller;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import fzdy.entity.DeviceAlarm;
import fzdy.entity.DeviceData;
import fzdy.entity.DeviceInfo;
import fzdy.entity.DeviceMalfunction;
import fzdy.service.IDeviceAlarmService;
import fzdy.service.IDeviceDataService;
import fzdy.service.IDeviceInfoService;
import fzdy.service.IDeviceMalfunctionService;
import fzdy.struct.DevicePostData;
import fzdy.struct.DevicePostInfo;
import fzdy.struct.MobileCache;
import fzdy.struct.SmsType;
import fzdy.tools.SmsSender;
import fzdy.tools.SpringContextUtil;
import fzdy.tools.TimeStampTool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.sql.Timestamp;

/**
 * Created by Administrator on 2018/1/4 0004.
 */
@Controller
@RequestMapping(value = "/sysmanage")
public class DataHandlingController {

    @Autowired
    private IDeviceInfoService deviceInfoService;
    @Autowired
    private IDeviceDataService deviceDataService;
    @Autowired
    private IDeviceMalfunctionService deviceMalfunctionService;
    @Autowired
    private IDeviceAlarmService deviceAlarmService;

    @RequestMapping(value = "/test")
    @ResponseBody
    public void test(@RequestBody DevicePostData devicePostData) {
        DeviceInfo device = deviceInfoService.get(devicePostData.getSn());
        if (device == null) {
            return;
        }
        device.setStatus(devicePostData.getStatus());
        deviceInfoService.updateT(device);
        addDeviceData(devicePostData, device);
        socketSendData(devicePostData, device);
        socketSendError(devicePostData, device);
    }

    /**
     * 将设备上报的数据添加到数据库中
     */
    private void addDeviceData(DevicePostData devicePostData, DeviceInfo device) {
        DeviceData data = new DeviceData();
        data.setDeviceSn(device.getSn());
        data.setData(JSON.toJSONString(device));
        data.setReceivedTime(new Timestamp(System.currentTimeMillis()));
        data.setReportTime(new Timestamp(devicePostData.getCreatetime().getTime()));
        data.setStatus(devicePostData.getStatus());
        Integer dataId = (Integer) deviceDataService.insertT(data);
        addDeviceErrorToDB(devicePostData, device, dataId);
    }

    /**
     * 将设备上报的故障或者火灾添加到对应数据库中
     */
    private void addDeviceErrorToDB(DevicePostData devicePostData, DeviceInfo device, Integer dataId) {
        if (devicePostData.getStatus() == 0) {
            return;
        } else if (devicePostData.getStatus() == 1) {
            DeviceMalfunction deviceMalfunction = new DeviceMalfunction();
            deviceMalfunction.setDeviceSn(device.getSn());
            deviceMalfunction.setMalfunctionTime(new Timestamp(devicePostData.getCreatetime().getTime()));
            deviceMalfunction.setDeviceDataId(dataId);
            deviceMalfunction.setFinished(false);
            deviceMalfunctionService.insertT(deviceMalfunction);
        } else if (devicePostData.getStatus() == 2) {
            DeviceAlarm deviceAlarm = new DeviceAlarm();
            deviceAlarm.setDataId(dataId);
            deviceAlarm.setDeviceSn(device.getSn());
            deviceAlarm.setReportTime(new Timestamp(devicePostData.getCreatetime().getTime()));
            deviceAlarmService.insertT(deviceAlarm);
        }

    }

    /**
     * 将设备上报的传给电脑前台，前台更新设备状态
     */
    private void socketSendData(DevicePostData devicePostData, DeviceInfo device) {
        devicePostData.setLocation(device.getLocation());
        devicePostData.setLat(device.getLat());
        devicePostData.setLng(device.getLng());
        devicePostData.setEndpointtype(0);
        devicePostData.setMessagetype(0);
        devicePostData.setDeviceTypeId(device.getDeviceTypeId());
        devicePostData.setManufacturer(device.getManufacturer());
        devicePostData.setProprietorUnit(device.getProprietorUnit().getUnitName());
        try {
            MyWebSocket.sendInfo(JSON.toJSONString(devicePostData));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 将设备故障或者火灾报警的数据传给电脑前台
     */
    private void socketSendError(DevicePostData devicePostData, DeviceInfo device) {
        DevicePostInfo devicePostInfo = new DevicePostInfo();
        devicePostInfo.setEndpointtype(0);
        devicePostInfo.setMessagetype(1);
        if (devicePostData.getStatus() == 0) {
            return;
        } else if (devicePostData.getStatus() == 1 && !MobileCache.isExistMobile(devicePostData.getSn())) {
            String logcontent;
            String info = device.getProprietorUnit().getUnitName() + device.getLocation() +"58";
            String reportTime = TimeStampTool.DateToString("yyyy-MM-dd HH:mm:ss", devicePostData.getCreatetime());
            devicePostInfo.setReportlogtype(1);
            logcontent = "您好," + info + "，于" + reportTime + "产生火灾报警";
            devicePostInfo.setLogcontent(logcontent);
            MobileCache.addData(devicePostData);
            JSONObject json58 = new JSONObject();
            json58.put("param1", device.getProprietorUnit().getUnitName());
            json58.put("param2", device.getLocation());
            json58.put("param3", reportTime);
//            sendSms(json58, SmsType.Device_FireAlarm, device.getProprietorUnit().getProprietorContact());
            System.out.println(111);
            JSONObject json59 = new JSONObject();
            json58.put("param1", info);
            json58.put("param2", reportTime);
//            sendSms(json59, SmsType.Device_FireChargeManNotice, device.getProprietorUnit().getProprietorContact());
        } else if (devicePostData.getStatus() == 2 && !MobileCache.isExistMobile(devicePostData.getSn())) {
            String logcontent;
            String info = device.getLocation() + device.getDeviceType().getDeviceType() + device.getDeviceName();
            String reportTime = TimeStampTool.DateToString("yyyy-MM-dd HH:mm:ss", devicePostData.getCreatetime());
            devicePostInfo.setReportlogtype(0);
            logcontent = "您好，所属的业主单位" + device.getProprietorUnit().getUnitName() + "，安装于" + info + "，在" + reportTime + "产生故障报警";
            devicePostInfo.setLogcontent(logcontent);
            MobileCache.addData(devicePostData);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("param1", device.getProprietorUnit().getUnitName());
            jsonObject.put("param2", info);
            jsonObject.put("param3", reportTime);
//            sendSms(jsonObject, SmsType.Device_FaultAlarm, device.getProprietorUnit().getProprietorContact());
        }
        try {
            MyWebSocket.sendInfo(JSON.toJSONString(devicePostInfo));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    private void sendSms(JSONObject jsonObject, SmsType type, String tel) {

        ((SmsSender) SpringContextUtil.getBean("smssender")).sendSms(type, tel, jsonObject.toString());
    }
}
